package it.apiconsulting.sharem.dao;


import it.apiconsulting.sharem.controller.bean.GuestBean;
import it.apiconsulting.sharem.model.Guest;
import it.apiconsulting.sharem.util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;


public class GuestDao extends HibernateUtil {
	
	public GuestBean add(GuestBean guest) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(copyBeansGbToG(guest));
		session.getTransaction().commit();
		return guest;
	}
	public GuestBean delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Guest guest = (Guest) session.load(Guest.class, id);
		if(null != guest) {
			session.delete(guest);
		}
		session.getTransaction().commit();
		return copyBeansGoGb(guest);
	}

	public List<GuestBean> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Guest> guests = null;
		List<GuestBean> guestsBean = new ArrayList<GuestBean>();
		try {
			
			Query query = session.createQuery("from Guest");
			guests = (List<Guest>)query.list();
			for (Guest guest : guests ) {
				guestsBean.add(copyBeansGoGb(guest));
			}
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return guestsBean;
	}
	
	public List<Guest> listByIdUser( Long idUser ) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Guest> guests = null;
		try {
			
			Query query = session.createQuery("from Guest as g where g.idUser=" + idUser);
			guests = (List<Guest>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return guests;
	}
	
	public GuestBean copyBeansGoGb(Guest guest){
		GuestBean gb = new GuestBean();
		gb.setDatacreazione(guest.getDatacreazione());
		gb.setId(guest.getId());
		gb.setIdUser(guest.getIdUser());
		gb.setUsername(guest.getUsername());
		return gb;
	}
	
	public Guest copyBeansGbToG(GuestBean guest){
		Guest g = new Guest();
		g.setDatacreazione(guest.getDatacreazione());
		g.setId(guest.getId());
		g.setIdUser(guest.getIdUser());
		g.setUsername(guest.getUsername());
		return g;
	}
}
